import { createSlice } from "@reduxjs/toolkit";
import { setToken as _setToken, getToken, removeToken } from "@/utils";
import { loginApi, getProfileApi } from "@/apis/user";

const userSlice = createSlice({
    name: 'user',
    initialState: {
        token: getToken() || '',
        user: {}
    },
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            _setToken(action.payload)
        },
        setUser(state, action) {
            state.user = action.payload
        },
        logout(state) {
            state.token = ''
            state.user = {}
            removeToken()
        }
    }
})

const { setToken, setUser, logout } = userSlice.actions
const userReducer = userSlice.reducer

const fetchLogin = (formData) => {
    return async (dispatch) => {
        console.log('fetchLoginform', formData)
        await loginApi(formData)
            .then(res => {
                console.log('fetchLogin', res)
                if (res && res.data !== null) {
                    dispatch(setToken(res.data.token))
                    return res
                }
            })
            .catch(error => {
                throw error;
            })
    }
}

const fetUserInfo = () => {
    return async (dispatch) => {
        getProfileApi()
            .then(res => {
                if (res.data !== null) {
                    dispatch(setUser(res.data))
                }
            })
    }
}

export { fetchLogin, fetUserInfo, logout }

export default userReducer